Self-Driving Car Engineer Nanodegree

Deep Learning

Project: Build a Traffic Sign Recognition Classifier

In this notebook, a template is provided for you to implement your functionality in stages, which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission if necessary.

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there is a writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a write up template that can be used to guide the writing process. Completing the code template and writeup template will cover all of the rubric points for this project.

The rubric contains "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. The stand out suggestions are optional. If you decide to pursue the "stand out suggestions", you can include the code in this Ipython notebook and also discuss the results in the writeup file.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.


Step 0: Load The Data

In [1]:
# Load pickled data
import pickle

floyd_hub = True

if floyd_hub:
    location_prefix = '/'
else:
    location_prefix = './'

training_file = location_prefix + 'datasets/train.p'
validation_file = location_prefix + 'datasets/valid.p'
testing_file = location_prefix + 'datasets/test.p'

with open(training_file, mode='rb') as f:
    train = pickle.load(f)
with open(validation_file, mode='rb') as f:
    valid = pickle.load(f)
with open(testing_file, mode='rb') as f:
    test = pickle.load(f)
    
X_train, y_train = train['features'], train['labels']
X_valid, y_valid = valid['features'], valid['labels']
X_test, y_test = test['features'], test['labels']

assert(len(X_train) == len(y_train))
assert(len(X_valid) == len(y_valid))
assert(len(X_test) == len(y_test))

print('Datasets loaded.')
Datasets loaded.

Step 1: Dataset Summary & Exploration

The pickled data is a dictionary with 4 key/value pairs:

  • 'features' is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).
  • 'labels' is a 1D array containing the label/class id of the traffic sign. The file signnames.csv contains id -> name mappings for each id.
  • 'sizes' is a list containing tuples, (width, height) representing the original width and height the image.
  • 'coords' is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGES

Complete the basic data summary below. Use python, numpy and/or pandas methods to calculate the data summary rather than hard coding the results. For example, the pandas shape method might be useful for calculating some of the summary results.

Provide a Basic Summary of the Data Set Using Python, Numpy and/or Pandas

In [2]:
### Replace each question mark with the appropriate value. 
### Use python, pandas or numpy methods rather than hard coding the results
import numpy as np

print('Numpy imported.')
Numpy imported.
In [3]:
# Summarize data

'''
print(X_train.shape[0])
print(X_valid.shape[0])
print(X_test.shape[0])
print(X_train.shape[1:4])
print(y_train.shape)
print(y_train.T)
'''

# TODO: Number of training examples
n_train = X_train.shape[0]

# TODO: Number of validation examples
n_validation = X_valid.shape[0]

# TODO: Number of testing examples.
n_test = X_test.shape[0]

# TODO: What's the shape of an traffic sign image?
image_shape = X_train.shape[1:4]

# TODO: How many unique classes/labels there are in the dataset.
n_classes = len(set(np.concatenate((y_train, y_valid, y_test), axis=0)))

print("Number of training examples =", n_train)
print("Number of testing examples =", n_test)
print("Image data shape =", image_shape)
print("Number of classes =", n_classes)
Number of training examples = 34799
Number of testing examples = 12630
Image data shape = (32, 32, 3)
Number of classes = 43

Include an exploratory visualization of the dataset

Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc.

The Matplotlib examples and gallery pages are a great resource for doing visualizations in Python.

NOTE: It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections. It can be interesting to look at the distribution of classes in the training, validation and test set. Is the distribution the same? Are there more examples of some classes than others?

In [4]:
### Data exploration visualization code goes here.
### Feel free to use as many code cells as needed.
import random
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
# Visualizations will be shown in the notebook.
%matplotlib inline

print('Graphiing liraries loaded.')
Graphiing liraries loaded.
In [5]:
import csv

### Load the label names
with open('./signnames.csv') as csvfile:
    csvfile.readline()
    labelreader = csv.reader(csvfile, delimiter=',')
    sign_labels = dict(labelreader)
    sign_labels = {int(k):v for k,v in sign_labels.items()}

print('Label names lookup loaded.')
Label names lookup loaded.
In [6]:
fig, axes = plt.subplots(6, 3, figsize=(15, 30), dpi=300)
fig.subplots_adjust(hspace=0.3, wspace=0.3)

for i, ax in enumerate(axes.flat):
    index = random.randint(0, n_train)
    image = X_train[index].squeeze()

    ax.imshow(image)
    classId = y_train[index]
    ax.set_xlabel(str(classId) + " - " + sign_labels.get(classId))

plt.show()
In [7]:
### Aggregate counts for labels in training set
unique, counts = np.unique(y_train, return_counts=True)
y_train_counts = dict(zip(unique, counts))
###print(y_train_counts)

### Aggregate counts for labels in validation set
unique, counts = np.unique(y_valid, return_counts=True)
y_valid_counts = dict(zip(unique, counts))
###print(y_valid_counts)

### Aggregate counts for labels in test set
unique, counts = np.unique(y_test, return_counts=True)
y_test_counts = dict(zip(unique, counts))
###print(y_test_counts)

###print(sign_labels.keys())
###print(sign_labels.items())

### Plot the counts to compare datasets
bar_chart, axes = plt.subplots(figsize=(20, 20))
plt.title('Sign Data Comparison', fontsize=16)

for k, v in y_train_counts.items():
    axes.bar(k - 0.3, v, width=0.3, color='b', align='center')

for k, v in y_valid_counts.items():
    axes.bar(k, v, width=0.3, color='r', align='center')

for k, v in y_test_counts.items():
    axes.bar(k + 0.3, v, width=0.3, color='g', align='center')

###plt.xticks(sign_labels.keys(), sign_labels.values(), rotation='vertical')
axes.set_ylim([0, 2100])
axes.set_xticks(list(sign_labels.keys()))
axes.set_xticklabels(list(sign_labels.values()), rotation='vertical')

axes.set_xlabel('Sign Names')
axes.set_ylabel('Total Count')

###legend = axes.legend(loc='upper right', shadow=True, fontsize='large')
###legend.get_frame().set_facecolor('#00FFCC')
blue_patch = mpatches.Patch(color='b', label='Train')
red_patch = mpatches.Patch(color='r', label='Validation')
green_patch = mpatches.Patch(color='g', label='Test')
legend = axes.legend(handles=[blue_patch, red_patch, green_patch], shadow=True, fontsize='x-large')

plt.show()

Step 2: Design and Test a Model Architecture

Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the German Traffic Sign Dataset.

The LeNet-5 implementation shown in the classroom at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play!

With the LeNet-5 solution from the lecture, you should expect a validation set accuracy of about 0.89. To meet specifications, the validation set accuracy will need to be at least 0.93. It is possible to get an even higher accuracy, but 0.93 is the minimum for a successful project submission.

There are various aspects to consider when thinking about this problem:

  • Neural network architecture (is the network over or underfitting?)
  • Play around preprocessing techniques (normalization, rgb to grayscale, etc)
  • Number of examples per label (some have more than others).
  • Generate fake data.

Here is an example of a published baseline model on this problem. It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.

Pre-process the Data Set (normalization, grayscale, etc.)

Minimally, the image data should be normalized so that the data has mean zero and equal variance. For image data, (pixel - 128)/ 128 is a quick way to approximately normalize the data and can be used in this project.

Other pre-processing steps are optional. You can try different techniques to see if it improves performance.

Use the code cell (or multiple code cells, if necessary) to implement the first step of your project.

In [8]:
### Preprocess the data here. It is required to normalize the data. Other preprocessing steps could include 
### converting to grayscale, etc.
### Feel free to use as many code cells as needed.
from sklearn.utils import shuffle
import cv2
import scipy.ndimage as scimg
import scipy.misc as misc

print('Data processing libraries loaded.')
Data processing libraries loaded.
In [9]:
# Converts color images to grayscale
def preprocess_images(images):
    # Setup for image sharpening
    #kernel = np.zeros( (9,9), np.float32)
    #kernel[4,4] = 2.0   #Identity, times two!
    
    #boxFilter = np.ones( (9,9), np.float32) / 81.0
    #kernel = kernel - boxFilter
    
    #print(images.shape[1:])
    #print(images.dtype)

    output = np.ndarray((images.shape[0], images.shape[1], images.shape[2], 1), dtype=images.dtype)
    for index, image in enumerate(images):
        #print(image.dtype)
        # Sharpen the images
        #image = cv2.filter2D(image, -1, kernel) / 255
        #image = image.astype(np.uint8)
        #print(image.dtype)
        
        # Convert to grayscale
        image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        image = cv2.equalizeHist(image)
        image = np.expand_dims(image, axis=2)
        output[index] = image
    
    return output

print('Function preprocess_images defined.')
Function preprocess_images defined.
In [10]:
# Augments data by creating various versions of the image set
# (Flip Horizontally, Flip Vertically, Zoomed In, and Rotated:
#  30, 60, 150, 240, 300, 330 degrees)
def augment_data(images, labels):
    num_images = images.shape[0]
    newImages = np.ndarray.copy(images)
    newLabels = np.ndarray.copy(labels)
    
    # Flip Horizontally
    for index, image in enumerate(images):
        newImages[index] = np.fliplr(image)
        newLabels[index] = labels[index]
    
    outputImages = np.concatenate((images, newImages), axis=0)
    outputLabels = np.concatenate((labels, newLabels), axis=0)
    
    # Flip Vertically
    for index, image in enumerate(images):
        newImages[index] = np.flipud(image)
        newLabels[index] = labels[index]
    
    outputImages = np.concatenate((outputImages, newImages), axis=0)
    outputLabels = np.concatenate((outputLabels, newLabels), axis=0)
    
    # Zoom image, retaining size
    for index, image in enumerate(images):
        zoomed = scimg.zoom(image, 1 + 0.05 * random.random())
        x1 = int((zoomed.shape[0] - image.shape[0]) / 2)
        y1 = int((zoomed.shape[1] - image.shape[1]) / 2)
        newImages[index] = zoomed[x1:x1 + image.shape[0], y1:y1 + image.shape[1]]
        newLabels[index] = labels[index]
    
    outputImages = np.concatenate((outputImages, newImages), axis=0)
    outputLabels = np.concatenate((outputLabels, newLabels), axis=0)
    """
    # Rotate image 30 degrees, retaining size
    for index, image in enumerate(images):
        newImages[index] = scimg.rotate(image, 30, reshape=False)
        newLabels[index] = labels[index]
    
    outputImages = np.concatenate((outputImages, newImages), axis=0)
    outputLabels = np.concatenate((outputLabels, newLabels), axis=0)
    
    # Rotate image 60 degrees, retaining size
    for index, image in enumerate(images):
        newImages[index] = scimg.rotate(image, 60, reshape=False)
        newLabels[index] = labels[index]
    
    outputImages = np.concatenate((outputImages, newImages), axis=0)
    outputLabels = np.concatenate((outputLabels, newLabels), axis=0)
    
    # Rotate image 150 degrees, retaining size
    for index, image in enumerate(images):
        newImages[index] = scimg.rotate(image, 150, reshape=False)
        newLabels[index] = labels[index]
    
    outputImages = np.concatenate((outputImages, newImages), axis=0)
    outputLabels = np.concatenate((outputLabels, newLabels), axis=0)
    
    # Rotate image 240 degrees, retaining size
    for index, image in enumerate(images):
        newImages[index] = scimg.rotate(image, 240, reshape=False)
        newLabels[index] = labels[index]
    
    outputImages = np.concatenate((outputImages, newImages), axis=0)
    outputLabels = np.concatenate((outputLabels, newLabels), axis=0)
    
    # Rotate image 300 degrees, retaining size
    for index, image in enumerate(images):
        newImages[index] = scimg.rotate(image, 300, reshape=False)
        newLabels[index] = labels[index]
    
    outputImages = np.concatenate((outputImages, newImages), axis=0)
    outputLabels = np.concatenate((outputLabels, newLabels), axis=0)
    
    # Rotate image 330 degrees, retaining size
    for index, image in enumerate(images):
        newImages[index] = scimg.rotate(image, 330, reshape=False)
        newLabels[index] = labels[index]
    
    outputImages = np.concatenate((outputImages, newImages), axis=0)
    outputLabels = np.concatenate((outputLabels, newLabels), axis=0)
    """
    
    # Rotate image 15 degrees, retaining size
    for index, image in enumerate(images):
        newImages[index] = scimg.rotate(image, 15, reshape=False)
        newLabels[index] = labels[index]
    
    outputImages = np.concatenate((outputImages, newImages), axis=0)
    outputLabels = np.concatenate((outputLabels, newLabels), axis=0)
    
    # Rotate image 330 degrees, retaining size
    for index, image in enumerate(images):
        newImages[index] = scimg.rotate(image, 330, reshape=False)
        newLabels[index] = labels[index]
    
    outputImages = np.concatenate((outputImages, newImages), axis=0)
    outputLabels = np.concatenate((outputLabels, newLabels), axis=0)

    return (outputImages, outputLabels)

print('Function augment_data defined.')
Function augment_data defined.
In [11]:
# Pre-process the data, creating new variables in order to make this single step repeatable

# Shuffle the training data
X_train, y_train = shuffle(X_train, y_train)

# Pre-process the training data
X_train_processed, y_train_processed = preprocess_images(X_train), y_train
X_train_processed, y_train_processed = augment_data(X_train_processed, y_train_processed)
X_train_processed, y_train_processed = shuffle(X_train_processed, y_train_processed)
n_train_processed = X_train_processed.shape[0]

X_train_processed = X_train_processed.astype(np.float32)

print("Min Training Data Value pre-normalization: {}".format(np.min(X_train_processed)))
print("Max Training Data Value pre-normalization: {}".format(np.max(X_train_processed)))
#X_train -= np.mean(X_train, axis = 0)
#X_train /= np.std(X_train, axis = 0)
X_train_processed -= 128.0
X_train_processed /= 128.0
print("Min Training Data Value post-normalization: {}".format(np.min(X_train_processed)))
print("Max Training Data Value post-normalization: {}".format(np.max(X_train_processed)))

# Pre-process the validation data
X_valid_processed, y_valid_processed = preprocess_images(X_valid), y_valid
n_valid_processed = X_valid_processed.shape[0]

X_valid_processed = X_valid_processed.astype(np.float32)

#X_valid -= np.mean(X_valid, axis = 0)
#X_valid /= np.std(X_valid, axis = 0)
X_valid_processed -= 128.0
X_valid_processed /= 128.0

print()
print('Pre-processing train/validation data completed.')
/usr/local/lib/python3.5/site-packages/scipy/ndimage/interpolation.py:600: UserWarning: From scipy 0.13.0, the output shape of zoom() is calculated with round() instead of int() - for these inputs the size of the returned array has changed.
  "the returned array has changed.", UserWarning)
Min Training Data Value pre-normalization: 0.0
Max Training Data Value pre-normalization: 255.0
Min Training Data Value post-normalization: -1.0
Max Training Data Value post-normalization: 0.9921875

Pre-processing train/validation data completed.
In [12]:
print("Pre-processed Training Data Shape: {}".format(X_train_processed.shape))
print("Pre-processed Validation Data Shape: {}".format(X_valid_processed.shape))
Pre-processed Training Data Shape: (208794, 32, 32, 1)
Pre-processed Validation Data Shape: (4410, 32, 32, 1)
In [13]:
fig, axes = plt.subplots(6, 3, figsize=(15, 30), dpi=300)
fig.subplots_adjust(hspace=0.3, wspace=0.3)

for i, ax in enumerate(axes.flat):
    index = random.randint(0, n_train)
    image = X_train_processed[index].squeeze()

    ax.imshow(image, cmap="gray")
    classId = y_train_processed[index]
    ax.set_xlabel(str(classId) + " - " + sign_labels.get(classId))

plt.show()

Model Architecture

In [14]:
### Define your architecture here.
### Feel free to use as many code cells as needed.
In [15]:
import tensorflow as tf
import datetime

# Set training parameters
EPOCHS = 100 # may not be used
BATCH_SIZE = 128

print('Model/training libraries loaded and parameters set.')
Model/training libraries loaded and parameters set.
In [16]:
from tensorflow.contrib.layers import flatten

def LeNet(x, keep_prob):    
    # Arguments used for tf.truncated_normal, randomly defines variables for the weights and biases for each layer
    mu = 0
    sigma = 0.1
    
    # Layer 1: Convolutional. Input = 32x32x1. Output = 28x28x16.
    conv1_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 1, 16), mean = mu, stddev = sigma))
    conv1_b = tf.Variable(tf.zeros(16))
    conv1   = tf.add(tf.nn.conv2d(x, conv1_W, strides=[1, 1, 1, 1], padding='VALID', name='conv1'),
                     conv1_b, name='conv1bias')

    #print("Convolution 1 Shape: {}".format(conv1.get_shape()))
    
    # Activation.
    conv1 = tf.nn.relu(conv1, name='conv1relu')

    # Pooling. Input = 28x28x16. Output = 14x14x16.
    conv1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID', name='conv1maxpool')

    #print("Convolution 1 Max Pool Shape: {}".format(conv1.get_shape()))
    
    # Dropout
    #conv1 = tf.nn.dropout(conv1, keep_prob, name='conv1dropout')

    # Layer 2: Convolutional. Output = 14x14x32.
    conv2_W = tf.Variable(tf.truncated_normal(shape=(3, 3, 16, 32), mean = mu, stddev = sigma))
    conv2_b = tf.Variable(tf.zeros(32))
    conv2   = tf.add(tf.nn.conv2d(conv1, conv2_W, strides=[1, 1, 1, 1], padding='SAME', name='conv2'),
                     conv2_b, name='conv2bias')

    #print("Convolution 2 Shape: {}".format(conv2.get_shape()))
    
    # Activation.
    conv2 = tf.nn.relu(conv2, name='conv2relu')

    # Pooling. Input = 14x14x32. Output = 7x7x32.
    conv2 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name='conv2maxpool')

    #print("Convolution 2 Max Pool Shape: {}".format(conv2.get_shape()))
    
    # Dropout
    #conv2 = tf.nn.dropout(conv2, keep_prob, name='conv2dropout')
    
    # Layer 3: Convolutional. Output = 7x7x64.
    conv3_W = tf.Variable(tf.truncated_normal(shape=(1, 1, 32, 64), mean = mu, stddev = sigma))
    conv3_b = tf.Variable(tf.zeros(64))
    conv3   = tf.add(tf.nn.conv2d(conv2, conv3_W, strides=[1, 1, 1, 1], padding='SAME', name='conv3'),
                     conv3_b, name='conv3bias')

    #print("Convolution 3 Shape: {}".format(conv3.get_shape()))
    
    # Activation.
    conv3 = tf.nn.relu(conv3, name='conv3relu')

    # Pooling. Input = 7x7x64. Output = 4x4x64.
    conv3 = tf.nn.max_pool(conv3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name='conv3maxpool')

    #print("Convolution 3 Max Pool Shape: {}".format(conv3.get_shape()))
    
    # Dropout
    #conv3 = tf.nn.dropout(conv3, keep_prob, name='conv3dropout')
    
    """ Removing layers 4 and 5 as the visualizations appear to provide no value
    # Layer 4: Convolutional. Output = 4x4x64.
    conv4_W = tf.Variable(tf.truncated_normal(shape=(1, 1, 32, 64), mean = mu, stddev = sigma))
    conv4_b = tf.Variable(tf.zeros(64))
    conv4   = tf.add(tf.nn.conv2d(conv3, conv4_W, strides=[1, 1, 1, 1], padding='SAME', name='conv4'),
                     conv4_b, name='conv4bias')

    #print("Convolution 4 Shape: {}".format(conv4.get_shape()))
    
    # Activation.
    conv4 = tf.nn.relu(conv4, name='conv4relu')

    # Pooling. Input = 4x4x64. Output = 2x2x64.
    conv4 = tf.nn.max_pool(conv4, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name='conv4maxpool')

    #print("Convolution 4 Max Pool Shape: {}".format(conv4.get_shape()))
    
    # Dropout
    #conv4 = tf.nn.dropout(conv4, keep_prob, name='conv4dropout')
    
    # Layer 5: Convolutional. Output = 2x2x256.
    conv5_W = tf.Variable(tf.truncated_normal(shape=(1, 1, 64, 256), mean = mu, stddev = sigma))
    conv5_b = tf.Variable(tf.zeros(256))
    conv5   = tf.add(tf.nn.conv2d(conv4, conv5_W, strides=[1, 1, 1, 1], padding='SAME', name='conv5'),
                     conv5_b, name='conv5bias')

    #print("Convolution 5 Shape: {}".format(conv5.get_shape()))
    
    # Activation.
    conv5 = tf.nn.relu(conv5, name='conv5relu')

    # Pooling. Input = 2x2x256. Output = 1x1x256.
    conv5 = tf.nn.max_pool(conv5, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name='conv5maxpool')

    #print("Convolution 5 Max Pool Shape: {}".format(conv5.get_shape()))
    
    # Dropout
    #conv5 = tf.nn.dropout(conv5, keep_prob, name='conv4dropout')
    """

    # Flatten. Input = 4x4x64. Output = 1024.
    fc0   = flatten(conv3)

    #print("Flatten Shape: {}".format(fc0.get_shape()))
    
    # Layer 4: Fully Connected. Input = 1024. Output = 120.
    fc1_W = tf.Variable(tf.truncated_normal(shape=(1024, 120), mean = mu, stddev = sigma))
    fc1_b = tf.Variable(tf.zeros(120))
    fc1   = tf.add(tf.matmul(fc0, fc1_W, name='fc1'), fc1_b, name='fc1bias')
    
    #print("Fully Connected 1 Shape: {}".format(fc1.get_shape()))
    
    # Activation.
    fc1    = tf.nn.relu(fc1, name='fc1relu')
    
    # Dropout
    fc1 = tf.nn.dropout(fc1, keep_prob, name='fc1dropout')
    
    # Layer 5: Fully Connected. Input = 120. Output = 84.
    fc2_W  = tf.Variable(tf.truncated_normal(shape=(120, 84), mean = mu, stddev = sigma))
    fc2_b  = tf.Variable(tf.zeros(84))
    fc2    = tf.add(tf.matmul(fc1, fc2_W, name='fc2'), fc2_b, name='fc2bias')
    
    #print("Fully Connected 2 Shape: {}".format(fc2.get_shape()))
    
    # Activation.
    fc2    = tf.nn.relu(fc2, name='fc2relu')
    
    # Dropout
    fc2 = tf.nn.dropout(fc2, keep_prob, name='fc2dropout')

    # Layer 6: Fully Connected. Input = 84. Output = 43.
    fc3_W  = tf.Variable(tf.truncated_normal(shape=(84, n_classes), mean = mu, stddev = sigma))
    fc3_b  = tf.Variable(tf.zeros(n_classes))
    logits = tf.add(tf.matmul(fc2, fc3_W, name='fc3'), fc3_b, name='fc3bias')
    
    #print("Fully Connected 3 Shape: {}".format(logits.get_shape()))
    
    return logits

print('Model architecture defined.')
Model architecture defined.
In [17]:
x = tf.placeholder(tf.float32, (None, 32, 32, 1), name='x')
y = tf.placeholder(tf.int32, (None), name='y')
keep_prob = tf.placeholder(tf.float32, name='keep_prob')
one_hot_y = tf.one_hot(y, n_classes)

print('Tensor placeholders defined.')
Tensor placeholders defined.

Train, Validate and Test the Model

A validation set can be used to assess how well the model is performing. A low accuracy on the training and validation sets imply underfitting. A high accuracy on the training set but low accuracy on the validation set implies overfitting.

In [18]:
### Train your model here.
### Calculate and report the accuracy on the training and validation set.
### Once a final model architecture is selected, 
### the accuracy on the test set should be calculated and reported as well.
### Feel free to use as many code cells as needed.
In [19]:
# Define training operations and parameters
rate = 0.0001

logits = LeNet(x, keep_prob)
logits = tf.identity(logits, name='logits')

cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=one_hot_y, logits=logits)
loss_operation = tf.reduce_mean(cross_entropy)
optimizer = tf.train.AdamOptimizer(learning_rate = rate)
training_operation = optimizer.minimize(loss_operation)

print('Training and optimizations defined.')
Training and optimizations defined.
In [20]:
# Define methods to make predictions and evaluate accuracy
prediction = tf.argmax(logits, 1, name='prediction')
correct_prediction = tf.equal(prediction, tf.argmax(one_hot_y, 1), name='correct_prediction')
accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32), name='accuracy')
saver = tf.train.Saver()

def evaluate(X_data, y_data, keep_probability):
    num_examples = len(X_data)
    total_accuracy = 0
    total_loss = 0
    sess = tf.get_default_session()
    for offset in range(0, num_examples, BATCH_SIZE):
        batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE]
        loss, accuracy = sess.run([loss_operation, accuracy_operation], feed_dict={x: batch_x, y: batch_y, keep_prob: keep_probability})
        total_accuracy += (accuracy * len(batch_x))
        total_loss += (loss * len(batch_x))
    return (total_loss / num_examples), (total_accuracy / num_examples)

print('Evaulation and prediction functions defined.')
Evaulation and prediction functions defined.
In [21]:
#
# Train the network
#

# Create a sesion
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    
    print("Training...")
    print()
    
    print('Start time: {}'.format(datetime.datetime.utcnow()))
    print()
    
    # Keep track of the loss/accuracy during training and validation
    train_loss_history = []
    train_accuracy_history = []
    validation_loss_history = []
    validation_accuracy_history = []

    train_loss = train_acc = valid_loss = valid_acc = 0.0
    epochs_ran = 0
    
    for i in range(EPOCHS):
        #while valid_acc <= 0.96:
        epochs_ran += 1
        X_train_processed, y_train_processed = shuffle(X_train_processed, y_train_processed)
        batch_i = 0
        train_loss = 0.0
        train_acc = 0.0
        for offset in range(0, n_train_processed, BATCH_SIZE):
            batch_i += 1
            end = offset + BATCH_SIZE
            batch_x, batch_y = X_train_processed[offset:end], y_train_processed[offset:end]
            _, batch_loss, batch_acc = sess.run([training_operation, loss_operation, accuracy_operation],
                                                feed_dict={x: batch_x, y: batch_y, keep_prob: 0.65})
            train_loss += (batch_loss * len(batch_x))
            train_acc += (batch_acc * len(batch_x))
            
        # Calculate loss and accuracy for epoch
        train_loss /= n_train_processed
        train_acc /= n_train_processed
        valid_loss, valid_acc = evaluate(X_valid_processed, y_valid_processed, 1.0)
        
        # Display stats for epoch - loss and accuracy
        print("EPOCH {:>3}:  ".format(epochs_ran), end='')
        print("Training Loss = {:>6.4f}, Training Accuracy = {:.3f}, Validation Loss = {:>6.4f}, Validation Accuracy = {:.3f}".format(
            train_loss, train_acc, valid_loss, valid_acc))
        
        # Log loss and accuracy for later use
        train_loss_history.append(train_loss)
        train_accuracy_history.append(train_acc)
        validation_loss_history.append(valid_loss)
        validation_accuracy_history.append(valid_acc)
    
    print()
    print('End time: {}'.format(datetime.datetime.utcnow()))
    
    print()
    print("Training completed.")
    print()
    
    saver.save(sess, './traffic_sign')
    print("Model saved.")
Training...

Start time: 2017-11-20 01:33:09.415945

EPOCH   1:  Training Loss = 3.0203, Training Accuracy = 0.184, Validation Loss = 2.0232, Validation Accuracy = 0.422
EPOCH   2:  Training Loss = 2.0106, Training Accuracy = 0.388, Validation Loss = 1.5165, Validation Accuracy = 0.522
EPOCH   3:  Training Loss = 1.6525, Training Accuracy = 0.471, Validation Loss = 1.3032, Validation Accuracy = 0.593
EPOCH   4:  Training Loss = 1.4489, Training Accuracy = 0.527, Validation Loss = 1.1635, Validation Accuracy = 0.627
EPOCH   5:  Training Loss = 1.3021, Training Accuracy = 0.572, Validation Loss = 1.0399, Validation Accuracy = 0.671
EPOCH   6:  Training Loss = 1.1816, Training Accuracy = 0.611, Validation Loss = 0.9260, Validation Accuracy = 0.704
EPOCH   7:  Training Loss = 1.0799, Training Accuracy = 0.645, Validation Loss = 0.8289, Validation Accuracy = 0.740
EPOCH   8:  Training Loss = 0.9877, Training Accuracy = 0.675, Validation Loss = 0.7313, Validation Accuracy = 0.766
EPOCH   9:  Training Loss = 0.9161, Training Accuracy = 0.698, Validation Loss = 0.6731, Validation Accuracy = 0.781
EPOCH  10:  Training Loss = 0.8516, Training Accuracy = 0.718, Validation Loss = 0.6233, Validation Accuracy = 0.802
EPOCH  11:  Training Loss = 0.7952, Training Accuracy = 0.737, Validation Loss = 0.5934, Validation Accuracy = 0.806
EPOCH  12:  Training Loss = 0.7440, Training Accuracy = 0.755, Validation Loss = 0.5424, Validation Accuracy = 0.828
EPOCH  13:  Training Loss = 0.7012, Training Accuracy = 0.769, Validation Loss = 0.5225, Validation Accuracy = 0.829
EPOCH  14:  Training Loss = 0.6651, Training Accuracy = 0.781, Validation Loss = 0.4977, Validation Accuracy = 0.847
EPOCH  15:  Training Loss = 0.6309, Training Accuracy = 0.790, Validation Loss = 0.4598, Validation Accuracy = 0.858
EPOCH  16:  Training Loss = 0.6018, Training Accuracy = 0.801, Validation Loss = 0.4457, Validation Accuracy = 0.857
EPOCH  17:  Training Loss = 0.5732, Training Accuracy = 0.811, Validation Loss = 0.4455, Validation Accuracy = 0.849
EPOCH  18:  Training Loss = 0.5479, Training Accuracy = 0.819, Validation Loss = 0.4429, Validation Accuracy = 0.859
EPOCH  19:  Training Loss = 0.5268, Training Accuracy = 0.826, Validation Loss = 0.4124, Validation Accuracy = 0.867
EPOCH  20:  Training Loss = 0.5070, Training Accuracy = 0.833, Validation Loss = 0.4026, Validation Accuracy = 0.872
EPOCH  21:  Training Loss = 0.4847, Training Accuracy = 0.841, Validation Loss = 0.3955, Validation Accuracy = 0.874
EPOCH  22:  Training Loss = 0.4665, Training Accuracy = 0.847, Validation Loss = 0.3846, Validation Accuracy = 0.877
EPOCH  23:  Training Loss = 0.4560, Training Accuracy = 0.850, Validation Loss = 0.3887, Validation Accuracy = 0.880
EPOCH  24:  Training Loss = 0.4379, Training Accuracy = 0.856, Validation Loss = 0.3765, Validation Accuracy = 0.885
EPOCH  25:  Training Loss = 0.4225, Training Accuracy = 0.861, Validation Loss = 0.3525, Validation Accuracy = 0.892
EPOCH  26:  Training Loss = 0.4056, Training Accuracy = 0.866, Validation Loss = 0.3629, Validation Accuracy = 0.888
EPOCH  27:  Training Loss = 0.3952, Training Accuracy = 0.870, Validation Loss = 0.3485, Validation Accuracy = 0.889
EPOCH  28:  Training Loss = 0.3866, Training Accuracy = 0.874, Validation Loss = 0.3596, Validation Accuracy = 0.893
EPOCH  29:  Training Loss = 0.3741, Training Accuracy = 0.878, Validation Loss = 0.3422, Validation Accuracy = 0.899
EPOCH  30:  Training Loss = 0.3636, Training Accuracy = 0.882, Validation Loss = 0.3304, Validation Accuracy = 0.896
EPOCH  31:  Training Loss = 0.3510, Training Accuracy = 0.885, Validation Loss = 0.3142, Validation Accuracy = 0.904
EPOCH  32:  Training Loss = 0.3437, Training Accuracy = 0.887, Validation Loss = 0.3333, Validation Accuracy = 0.901
EPOCH  33:  Training Loss = 0.3356, Training Accuracy = 0.891, Validation Loss = 0.3217, Validation Accuracy = 0.905
EPOCH  34:  Training Loss = 0.3289, Training Accuracy = 0.892, Validation Loss = 0.3193, Validation Accuracy = 0.905
EPOCH  35:  Training Loss = 0.3206, Training Accuracy = 0.895, Validation Loss = 0.3104, Validation Accuracy = 0.904
EPOCH  36:  Training Loss = 0.3116, Training Accuracy = 0.898, Validation Loss = 0.3104, Validation Accuracy = 0.904
EPOCH  37:  Training Loss = 0.3056, Training Accuracy = 0.900, Validation Loss = 0.3186, Validation Accuracy = 0.907
EPOCH  38:  Training Loss = 0.2989, Training Accuracy = 0.902, Validation Loss = 0.3137, Validation Accuracy = 0.910
EPOCH  39:  Training Loss = 0.2919, Training Accuracy = 0.904, Validation Loss = 0.3006, Validation Accuracy = 0.910
EPOCH  40:  Training Loss = 0.2847, Training Accuracy = 0.907, Validation Loss = 0.3087, Validation Accuracy = 0.913
EPOCH  41:  Training Loss = 0.2783, Training Accuracy = 0.909, Validation Loss = 0.3115, Validation Accuracy = 0.910
EPOCH  42:  Training Loss = 0.2715, Training Accuracy = 0.911, Validation Loss = 0.2977, Validation Accuracy = 0.916
EPOCH  43:  Training Loss = 0.2664, Training Accuracy = 0.913, Validation Loss = 0.3044, Validation Accuracy = 0.913
EPOCH  44:  Training Loss = 0.2618, Training Accuracy = 0.914, Validation Loss = 0.3038, Validation Accuracy = 0.915
EPOCH  45:  Training Loss = 0.2561, Training Accuracy = 0.916, Validation Loss = 0.3040, Validation Accuracy = 0.912
EPOCH  46:  Training Loss = 0.2528, Training Accuracy = 0.918, Validation Loss = 0.3090, Validation Accuracy = 0.912
EPOCH  47:  Training Loss = 0.2486, Training Accuracy = 0.919, Validation Loss = 0.2796, Validation Accuracy = 0.916
EPOCH  48:  Training Loss = 0.2439, Training Accuracy = 0.920, Validation Loss = 0.3035, Validation Accuracy = 0.920
EPOCH  49:  Training Loss = 0.2384, Training Accuracy = 0.922, Validation Loss = 0.2786, Validation Accuracy = 0.918
EPOCH  50:  Training Loss = 0.2344, Training Accuracy = 0.923, Validation Loss = 0.2823, Validation Accuracy = 0.919
EPOCH  51:  Training Loss = 0.2301, Training Accuracy = 0.925, Validation Loss = 0.2905, Validation Accuracy = 0.919
EPOCH  52:  Training Loss = 0.2283, Training Accuracy = 0.925, Validation Loss = 0.2890, Validation Accuracy = 0.922
EPOCH  53:  Training Loss = 0.2222, Training Accuracy = 0.928, Validation Loss = 0.2859, Validation Accuracy = 0.920
EPOCH  54:  Training Loss = 0.2168, Training Accuracy = 0.929, Validation Loss = 0.2795, Validation Accuracy = 0.922
EPOCH  55:  Training Loss = 0.2147, Training Accuracy = 0.930, Validation Loss = 0.2686, Validation Accuracy = 0.922
EPOCH  56:  Training Loss = 0.2113, Training Accuracy = 0.931, Validation Loss = 0.2769, Validation Accuracy = 0.922
EPOCH  57:  Training Loss = 0.2088, Training Accuracy = 0.932, Validation Loss = 0.2918, Validation Accuracy = 0.922
EPOCH  58:  Training Loss = 0.2062, Training Accuracy = 0.932, Validation Loss = 0.2799, Validation Accuracy = 0.926
EPOCH  59:  Training Loss = 0.2028, Training Accuracy = 0.933, Validation Loss = 0.2849, Validation Accuracy = 0.925
EPOCH  60:  Training Loss = 0.2002, Training Accuracy = 0.934, Validation Loss = 0.2820, Validation Accuracy = 0.923
EPOCH  61:  Training Loss = 0.1981, Training Accuracy = 0.935, Validation Loss = 0.2720, Validation Accuracy = 0.927
EPOCH  62:  Training Loss = 0.1945, Training Accuracy = 0.937, Validation Loss = 0.2810, Validation Accuracy = 0.924
EPOCH  63:  Training Loss = 0.1899, Training Accuracy = 0.938, Validation Loss = 0.2774, Validation Accuracy = 0.927
EPOCH  64:  Training Loss = 0.1867, Training Accuracy = 0.939, Validation Loss = 0.2680, Validation Accuracy = 0.925
EPOCH  65:  Training Loss = 0.1847, Training Accuracy = 0.939, Validation Loss = 0.2923, Validation Accuracy = 0.924
EPOCH  66:  Training Loss = 0.1823, Training Accuracy = 0.941, Validation Loss = 0.2883, Validation Accuracy = 0.927
EPOCH  67:  Training Loss = 0.1790, Training Accuracy = 0.941, Validation Loss = 0.2711, Validation Accuracy = 0.928
EPOCH  68:  Training Loss = 0.1787, Training Accuracy = 0.941, Validation Loss = 0.2653, Validation Accuracy = 0.928
EPOCH  69:  Training Loss = 0.1743, Training Accuracy = 0.943, Validation Loss = 0.2811, Validation Accuracy = 0.926
EPOCH  70:  Training Loss = 0.1730, Training Accuracy = 0.944, Validation Loss = 0.2972, Validation Accuracy = 0.927
EPOCH  71:  Training Loss = 0.1699, Training Accuracy = 0.944, Validation Loss = 0.2757, Validation Accuracy = 0.926
EPOCH  72:  Training Loss = 0.1686, Training Accuracy = 0.945, Validation Loss = 0.2876, Validation Accuracy = 0.924
EPOCH  73:  Training Loss = 0.1663, Training Accuracy = 0.945, Validation Loss = 0.2873, Validation Accuracy = 0.928
EPOCH  74:  Training Loss = 0.1655, Training Accuracy = 0.946, Validation Loss = 0.2847, Validation Accuracy = 0.927
EPOCH  75:  Training Loss = 0.1609, Training Accuracy = 0.947, Validation Loss = 0.2993, Validation Accuracy = 0.927
EPOCH  76:  Training Loss = 0.1598, Training Accuracy = 0.947, Validation Loss = 0.2849, Validation Accuracy = 0.928
EPOCH  77:  Training Loss = 0.1583, Training Accuracy = 0.948, Validation Loss = 0.2865, Validation Accuracy = 0.927
EPOCH  78:  Training Loss = 0.1534, Training Accuracy = 0.950, Validation Loss = 0.2896, Validation Accuracy = 0.927
EPOCH  79:  Training Loss = 0.1535, Training Accuracy = 0.950, Validation Loss = 0.2885, Validation Accuracy = 0.930
EPOCH  80:  Training Loss = 0.1515, Training Accuracy = 0.950, Validation Loss = 0.3049, Validation Accuracy = 0.930
EPOCH  81:  Training Loss = 0.1500, Training Accuracy = 0.950, Validation Loss = 0.3207, Validation Accuracy = 0.930
EPOCH  82:  Training Loss = 0.1493, Training Accuracy = 0.951, Validation Loss = 0.3017, Validation Accuracy = 0.927
EPOCH  83:  Training Loss = 0.1473, Training Accuracy = 0.952, Validation Loss = 0.2952, Validation Accuracy = 0.932
EPOCH  84:  Training Loss = 0.1458, Training Accuracy = 0.953, Validation Loss = 0.2959, Validation Accuracy = 0.930
EPOCH  85:  Training Loss = 0.1431, Training Accuracy = 0.953, Validation Loss = 0.3041, Validation Accuracy = 0.930
EPOCH  86:  Training Loss = 0.1416, Training Accuracy = 0.953, Validation Loss = 0.3071, Validation Accuracy = 0.928
EPOCH  87:  Training Loss = 0.1411, Training Accuracy = 0.954, Validation Loss = 0.2915, Validation Accuracy = 0.931
EPOCH  88:  Training Loss = 0.1394, Training Accuracy = 0.954, Validation Loss = 0.3139, Validation Accuracy = 0.927
EPOCH  89:  Training Loss = 0.1374, Training Accuracy = 0.955, Validation Loss = 0.2910, Validation Accuracy = 0.927
EPOCH  90:  Training Loss = 0.1357, Training Accuracy = 0.956, Validation Loss = 0.3096, Validation Accuracy = 0.928
EPOCH  91:  Training Loss = 0.1344, Training Accuracy = 0.956, Validation Loss = 0.3023, Validation Accuracy = 0.929
EPOCH  92:  Training Loss = 0.1342, Training Accuracy = 0.956, Validation Loss = 0.3214, Validation Accuracy = 0.926
EPOCH  93:  Training Loss = 0.1327, Training Accuracy = 0.956, Validation Loss = 0.2875, Validation Accuracy = 0.932
EPOCH  94:  Training Loss = 0.1305, Training Accuracy = 0.956, Validation Loss = 0.3054, Validation Accuracy = 0.929
EPOCH  95:  Training Loss = 0.1289, Training Accuracy = 0.958, Validation Loss = 0.3175, Validation Accuracy = 0.932
EPOCH  96:  Training Loss = 0.1285, Training Accuracy = 0.958, Validation Loss = 0.3078, Validation Accuracy = 0.931
EPOCH  97:  Training Loss = 0.1278, Training Accuracy = 0.958, Validation Loss = 0.3053, Validation Accuracy = 0.929
EPOCH  98:  Training Loss = 0.1242, Training Accuracy = 0.959, Validation Loss = 0.3188, Validation Accuracy = 0.930
EPOCH  99:  Training Loss = 0.1253, Training Accuracy = 0.959, Validation Loss = 0.2967, Validation Accuracy = 0.932
EPOCH 100:  Training Loss = 0.1237, Training Accuracy = 0.959, Validation Loss = 0.3026, Validation Accuracy = 0.930

End time: 2017-11-20 01:56:58.229594

Training completed.

Model saved.
Chart for the model architecture's loss of the training and validation sets.
In [22]:
plt.figure(figsize=(10,5))
loss_plot = plt.subplot(2,1,1)
loss_plot.set_title('Loss', fontsize=16)
loss_plot.plot(train_loss_history, 'r', label='Training Loss')
loss_plot.plot(validation_loss_history, 'b', label='Validation Loss')
loss_plot.set_xlim([0, epochs_ran])
loss_plot.legend(loc=1)
plt.show()

Chart for the model architecure's accuracy of the training and vaidation sets.

In [23]:
plt.figure(figsize=(10,5))
accuracy_plot = plt.subplot(2,1,1)
accuracy_plot.set_title('Accuracy', fontsize=16)
accuracy_plot.plot(train_accuracy_history, 'r', label='Training Accuracy')
accuracy_plot.plot(validation_accuracy_history, 'b', label='Validation Accuracy')
accuracy_plot.set_xlim([0, epochs_ran])
accuracy_plot.set_ylim([0.0, 1.0])
accuracy_plot.legend(loc=4)
plt.show()

Pre-process the test data and evaluate the data against the trained network

In [24]:
# Pre-process the test data
X_test_processed, y_test_processed = preprocess_images(X_test), y_test

X_test_processed = X_test_processed.astype(np.float32)
#X_test -= np.mean(X_test, axis = 0)
#X_test /= np.std(X_test, axis = 0)
X_test_processed -= 128.0
X_test_processed /= 128.0

print('Pre-processing test data completed.')
Pre-processing test data completed.
In [25]:
# Create a session
with tf.Session() as sess:
    # Restore the saved model
    saver.restore(sess, tf.train.latest_checkpoint('.'))

    test_loss, test_acc = evaluate(X_test_processed, y_test_processed, 1.0)
    print("Testing Loss = {:>6.3f}, Testing Accuracy = {:.3f}".format(test_loss, test_acc))
Testing Loss =  0.314, Testing Accuracy = 0.928

Step 3: Test a Model on New Images

To give yourself more insight into how your model is working, download at least five pictures of German traffic signs from the web and use your model to predict the traffic sign type.

You may find signnames.csv useful as it contains mappings from the class id (integer) to the actual sign name.

Load and Output the Images

In [26]:
### Load the images and plot them here.
### Feel free to use as many code cells as needed.
from os import listdir
from os.path import isfile, join

classifications = {
    "German-Traffic-Sign-30kmph.jpg":1,
    "German-Traffic-Sign-120kmph.jpg":8,
    "German-Traffic-Sign-Children-Crossing.jpg":28,
    "German-Traffic-Sign-No-Entry.jpg":17,
    "German-Traffic-Sign-Pedestrian-Crossing.jpg":27,
    "German-Traffic-Sign-Pedestrians-Only.jpg":27,
    "German-Traffic-Sign-Road-Slippery.jpg":23,
    "German-Traffic-Sign-Road-Work.jpg":25,
    "German-Traffic-Sign-Roundabout.png":40,
    "German-Traffic-Sign-Ahead-Only.jpg":35,
    "German-Traffic-Sign-Bumpy-Road.jpg":22,
    "German-Traffic-Sign-Dangerous-Curve-To-Left.jpg":19,
    "German-Traffic-Sign-Dobule-Curve.jpg":21,
    "German-Traffic-Sign-General-Caution.jpg":18,
    "German-Traffic-Sign-No-Passing.jpg":9,
    "German-Traffic-Sign-Stop.jpg":14,
    "German-Traffic-Sign-Wild-Animals-Crossing.jpg":31,
    "German-Traffic-Sign-Yield.jpg":13,
    "German-Traffic-Sign-Bicycles-Crossing.jpg":29,
    "German-Traffic-Sign-Traffic-Signals-Ahead.jpg":26,
    "German-Traffic-Sign-Go-Straight-Or-Right.jpg":36
}

new_image_path = './new-images'
X_new_images = []
y_new_images = []
for file_name in listdir(new_image_path):
    file_path = join(new_image_path, file_name)
    if isfile(file_path):
        new_image = cv2.imread(file_path)
        new_image = cv2.cvtColor(new_image, cv2.COLOR_BGR2RGB)
        y_new_images.append(classifications[file_name])
        if new_image.shape == (32, 32, 3):
            X_new_images.append(new_image)
        else:
            X_new_images.append(misc.imresize(new_image, (32, 32, 3)))

X_new_images = np.array(X_new_images)
y_new_images = np.array(y_new_images)

print('New images loaded.')
New images loaded.
In [27]:
# Plot the new images loaded along with their classiification
fig, axes = plt.subplots(7, 3, figsize=(15, 35), dpi=300)
fig.subplots_adjust(hspace=0.3, wspace=0.3)

for i, ax in enumerate(axes.flat):
    image = X_new_images[i].squeeze()

    ax.imshow(image)
    classId = y_new_images[i]
    ax.set_xlabel(str(classId) + " - " + sign_labels.get(classId))

plt.show()

Predict the Sign Type for Each Image

In [28]:
### Run the predictions here and use the model to output the prediction for each image.
### Make sure to pre-process the images with the same pre-processing pipeline used earlier.
### Feel free to use as many code cells as needed.
In [29]:
# Pre-process the test data
X_new_images_processed, y_new_images_processed = preprocess_images(X_new_images), y_new_images

X_new_images_processed = X_new_images_processed.astype(np.float32)
X_new_images_processed -= 128.0
X_new_images_processed /= 128.0

print('Pre-processing new image data completed.')
Pre-processing new image data completed.
In [30]:
# Plot the pre-processed images along with their classification
fig, axes = plt.subplots(7, 3, figsize=(15, 35), dpi=300)
fig.subplots_adjust(hspace=0.3, wspace=0.3)

for i, ax in enumerate(axes.flat):
    image = X_new_images_processed[i].squeeze()

    ax.imshow(image, cmap='gray')
    classId = y_new_images_processed[i]
    ax.set_xlabel(str(classId) + " - " + sign_labels.get(classId))

plt.show()
In [31]:
# Evaluate the predictions for the new images
predictions = np.array([])
softmax = np.array([])

# Create a session
with tf.Session() as sess:
    # Restore the saved model
    saver.restore(sess, tf.train.latest_checkpoint('.'))
    
    # Run the predictions
    predictions = sess.run(logits, feed_dict={x: X_new_images_processed, keep_prob: 1.0})
    softmax = sess.run(tf.nn.softmax(logits), feed_dict={logits: predictions})

print('Predictions and softmaxes computed.')
Predictions and softmaxes computed.

Analyze Performance

In [32]:
### Calculate the accuracy for these 5 new images. 
### For example, if the model predicted 1 out of 5 signs correctly, it's 20% accurate on these new images.
In [33]:
# Calculate the accuracy of the predictions for the new images
predicted_labels = np.argmax(predictions, axis=1)

match_count = sum([int(y == y_) 
                   for y, y_ in zip(y_new_images_processed, predicted_labels)])
accuracy = match_count / len(y_new_images_processed)
print("Accuracy: {:.3f}".format(accuracy))
Accuracy: 0.667

Plot the new images along with its actual label and predicted label

In [34]:
# Plot the new images with predicted vs actual classification
# This code is from Waleed Abdulla's work on GitHub @
# https://github.com/waleedka/traffic-signs-tensorflow/blob/master/notebook1.ipynb
fig, axes = plt.subplots(10, 2, figsize=(20, 35), dpi=300)
fig.subplots_adjust(hspace=0.3, wspace=0.3)

for i, ax in enumerate(axes.flat):
    actual_class_id = y_new_images[i]
    actual_class_label = str(actual_class_id) + " - " + sign_labels.get(actual_class_id)
    predicted_class_id = predicted_labels[i]
    predicted_class_label = str(predicted_class_id) + " - " + sign_labels.get(predicted_class_id)

    ax.axis('off')
    color = 'green' if actual_class_id == predicted_class_id else 'red'
    
    ax.text(40, 20, "Truth:        {0}\nPrediction: {1}".format(actual_class_label, predicted_class_label),
            fontsize=16, color=color)
    
    ax.imshow(X_new_images[i])

Output Top 5 Softmax Probabilities For Each Image Found on the Web

For each of the new images, print out the model's softmax probabilities to show the certainty of the model's predictions (limit the output to the top 5 probabilities for each image). tf.nn.top_k could prove helpful here.

The example below demonstrates how tf.nn.top_k can be used to find the top k predictions for each image.

tf.nn.top_k will return the values and indices (class ids) of the top k predictions. So if k=3, for each sign, it'll return the 3 largest probabilities (out of a possible 43) and the correspoding class ids.

Take this numpy array as an example. The values in the array represent predictions. The array contains softmax probabilities for five candidate images with six possible classes. tf.nn.top_k is used to choose the three classes with the highest probability:

# (5, 6) array
a = np.array([[ 0.24879643,  0.07032244,  0.12641572,  0.34763842,  0.07893497,
         0.12789202],
       [ 0.28086119,  0.27569815,  0.08594638,  0.0178669 ,  0.18063401,
         0.15899337],
       [ 0.26076848,  0.23664738,  0.08020603,  0.07001922,  0.1134371 ,
         0.23892179],
       [ 0.11943333,  0.29198961,  0.02605103,  0.26234032,  0.1351348 ,
         0.16505091],
       [ 0.09561176,  0.34396535,  0.0643941 ,  0.16240774,  0.24206137,
         0.09155967]])

Running it through sess.run(tf.nn.top_k(tf.constant(a), k=3)) produces:

TopKV2(values=array([[ 0.34763842,  0.24879643,  0.12789202],
       [ 0.28086119,  0.27569815,  0.18063401],
       [ 0.26076848,  0.23892179,  0.23664738],
       [ 0.29198961,  0.26234032,  0.16505091],
       [ 0.34396535,  0.24206137,  0.16240774]]), indices=array([[3, 0, 5],
       [0, 1, 4],
       [0, 5, 1],
       [1, 3, 5],
       [1, 4, 3]], dtype=int32))

Looking just at the first row we get [ 0.34763842, 0.24879643, 0.12789202], you can confirm these are the 3 largest probabilities in a. You'll also notice [3, 0, 5] are the corresponding indices.

In [35]:
### Print out the top five softmax probabilities for the predictions on the German traffic sign images found on the web. 
### Feel free to use as many code cells as needed.
In [36]:
# Create a session
with tf.Session() as sess:
    # Retreive the top 5 predictions
    top_5 = sess.run(tf.nn.top_k(tf.constant(softmax), k=5))

print(top_5)
TopKV2(values=array([[  9.97383416e-01,   2.10335804e-03,   3.27951333e-04,
          1.84401753e-04,   7.43320072e-07],
       [  9.99936223e-01,   4.33169989e-05,   9.25412951e-06,
          6.55818121e-06,   3.95856705e-06],
       [  9.56463456e-01,   2.55353823e-02,   1.30772023e-02,
          2.40886468e-03,   2.05828017e-03],
       [  9.99640703e-01,   3.48668022e-04,   1.05471017e-05,
          1.17046312e-07,   5.00810227e-10],
       [  9.76772845e-01,   1.49151916e-02,   6.06637495e-03,
          2.09599803e-03,   7.44784411e-05],
       [  8.77133369e-01,   5.00754975e-02,   2.90428437e-02,
          2.86027621e-02,   9.41071939e-03],
       [  9.76615787e-01,   2.29929611e-02,   3.91096924e-04,
          2.08960202e-07,   9.02090580e-09],
       [  1.00000000e+00,   9.79984427e-10,   2.15790805e-13,
          9.03704872e-14,   1.01188470e-14],
       [  3.56724054e-01,   3.38938057e-01,   2.90913194e-01,
          1.10149393e-02,   9.14344098e-04],
       [  8.35760355e-01,   1.50915295e-01,   1.05043789e-02,
          1.42748060e-03,   5.50938828e-04],
       [  9.99838233e-01,   1.40373333e-04,   1.14709801e-05,
          5.80861570e-06,   3.86796273e-06],
       [  9.97389853e-01,   2.06282642e-03,   3.49146605e-04,
          1.77480528e-04,   1.20298928e-05],
       [  8.36470664e-01,   1.05307020e-01,   3.50234210e-02,
          1.30649498e-02,   8.26127268e-03],
       [  9.43847716e-01,   4.07386310e-02,   1.47943739e-02,
          3.18480539e-04,   1.08101260e-04],
       [  9.63220775e-01,   3.61338891e-02,   6.45354507e-04,
          5.14098941e-09,   3.94383859e-09],
       [  8.62825632e-01,   1.36473402e-01,   6.36139419e-04,
          3.54932199e-05,   2.92149525e-05],
       [  9.99999881e-01,   9.58151531e-08,   1.56332813e-08,
          3.96052108e-10,   1.81656632e-12],
       [  1.00000000e+00,   1.30977604e-10,   1.63225911e-12,
          4.14399580e-13,   2.44193733e-15],
       [  9.99999046e-01,   5.55313420e-07,   3.47586422e-07,
          2.36555842e-08,   9.70926450e-10],
       [  9.99807060e-01,   1.76682108e-04,   1.04558103e-05,
          5.79021662e-06,   2.46868437e-09],
       [  9.99996066e-01,   3.98122120e-06,   3.82444965e-09,
          3.42105499e-09,   5.00046060e-10]], dtype=float32), indices=array([[36, 37, 33, 35, 11],
       [25, 28, 30, 24, 29],
       [29, 12, 28,  7,  8],
       [19, 20, 26, 27, 28],
       [28, 30, 11, 27, 24],
       [21, 11, 23, 30, 19],
       [23, 19, 20, 25, 30],
       [17, 33, 34, 14, 38],
       [ 6, 12, 11, 42, 28],
       [21, 31, 28, 11, 18],
       [14,  3, 29,  8,  0],
       [ 1,  4,  0,  2,  3],
       [19, 27, 20, 11, 26],
       [35, 25, 18, 24, 22],
       [12, 40,  7,  6,  1],
       [ 4,  3,  1, 14, 15],
       [18, 26, 24, 27, 13],
       [35, 33, 34,  3, 38],
       [13, 26, 18, 29, 22],
       [22, 29, 25, 13, 34],
       [25, 22, 28, 29, 30]], dtype=int32))

Plot new images along with their top 5 predicted labels

In [37]:
# Plot the new images with actual classification and top 5 predicted classifications
# This code is from Waleed Abdulla's work on GitHub @
# https://github.com/waleedka/traffic-signs-tensorflow/blob/master/notebook1.ipynb
fig, axes = plt.subplots(10, 2, figsize=(20, 35), dpi=300)
fig.subplots_adjust(hspace=0.3, wspace=0.3)

for i, ax in enumerate(axes.flat):
    label = ""
    for index in range(5):
        class_id = top_5.indices[i][index]
        label += "{}: {} - {}\n".format(index + 1, class_id, sign_labels.get(class_id))

    color = 'green' if y_new_images[i] == top_5.indices[i][0] else 'red'
    ax.title.set_color(color)
    ax.set_title("{} - {}".format(y_new_images[i], sign_labels.get(y_new_images[i])), fontsize=14)
    ax.axis('off')
    ax.text(40, 25, label, fontsize=14, color='black')
    ax.imshow(X_new_images[i])

plt.show()

Plot new images along with a bar chart of the top 5 predictions

In [38]:
# Plot the new images with actual classification and top 5 predicted classifications
fig, axes = plt.subplots(20, 2, figsize=(17, 35), dpi=300)
fig.subplots_adjust(hspace=0.3, wspace=0.3)

for i, ax in enumerate(axes.flat):
    if i % 2 == 0:
        index = int(i / 2)
        color = 'green' if y_new_images[index] == top_5.indices[index][0] else 'red'
        ax.title.set_color(color)
        ax.set_title("{} - {}".format(y_new_images[index], sign_labels.get(y_new_images[index])), fontsize=14)
        ax.axis('off')
        ax.imshow(X_new_images[index])
    else:
        index = int((i - 1) / 2)
        for k in range(len(top_5.values[index])):
            ax.barh(k + 1, top_5.values[index][k], color='b', align='center')
        ax.set_xlim([0, 1.0])
        y_labels = []
        y_labels.append(sign_labels.get(top_5.indices[index][0]))
        y_labels.append(sign_labels.get(top_5.indices[index][1]))
        y_labels.append(sign_labels.get(top_5.indices[index][2]))
        y_labels.append(sign_labels.get(top_5.indices[index][3]))
        y_labels.append(sign_labels.get(top_5.indices[index][4]))
        ax.set_yticks(list([1, 2, 3, 4, 5]))
        ax.set_yticklabels(list(y_labels))

plt.show()

Project Writeup

Once you have completed the code implementation, document your results in a project writeup using this template as a guide. The writeup can be in a markdown or pdf file.

Note: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.


Step 4 (Optional): Visualize the Neural Network's State with Test Images

This Section is not required to complete but acts as an additional excersise for understaning the output of a neural network's weights. While neural networks can be a great learning device they are often referred to as a black box. We can understand what the weights of a neural network look like better by plotting their feature maps. After successfully training your neural network you can see what it's feature maps look like by plotting the output of the network's weight layers in response to a test stimuli image. From these plotted feature maps, it's possible to see what characteristics of an image the network finds interesting. For a sign, maybe the inner network feature maps react with high activation to the sign's boundary outline or to the contrast in the sign's painted symbol.

Provided for you below is the function code that allows you to get the visualization output of any tensorflow weight layer you want. The inputs to the function should be a stimuli image, one used during training or a new one you provided, and then the tensorflow variable name that represents the layer's state during the training process, for instance if you wanted to see what the LeNet lab's feature maps looked like for it's second convolutional layer you could enter conv2 as the tf_activation variable.

For an example of what feature map outputs look like, check out NVIDIA's results in their paper End-to-End Deep Learning for Self-Driving Cars in the section Visualization of internal CNN State. NVIDIA was able to show that their network's inner weights had high activations to road boundary lines by comparing feature maps from an image with a clear path to one without. Try experimenting with a similar test to show that your trained network's weights are looking for interesting features, whether it's looking at differences in feature maps from images with or without a sign, or even what feature maps look like in a trained network vs a completely untrained one on the same sign image.

Combined Image

Your output should look something like this (above)

In [51]:
### Visualize your network's feature maps here.
### Feel free to use as many code cells as needed.

# image_input: the test image being fed into the network to produce the feature maps
# tf_activation: should be a tf variable name used during your training procedure that represents the calculated state of a specific weight layer
# activation_min/max: can be used to view the activation contrast in more detail, by default matplot sets min and max to the actual min and max values of the output
# plt_num: used to plot out multiple different weight feature map sets on the same block, just extend the plt number for each new feature map entry

def outputFeatureMap(image_input, tf_activation, activation_min=-1, activation_max=-1, plt_num=1):
    # Here make sure to preprocess your image_input in a way your network expects
    # with size, normalization, ect if needed
    # image_input =
    # Note: x should be the same name as your network's tensorflow data placeholder variable
    # If you get an error tf_activation is not defined it may be having trouble accessing the variable from inside a function
    activation = tf_activation.eval(session=sess, feed_dict={x : image_input, keep_prob : 1.0})
    featuremaps = activation.shape[3]
    plt.figure(plt_num, figsize=(50,40))
    for featuremap in range(featuremaps):
        plt.subplot(12,6, featuremap+1) # sets the number of feature maps to show on each row and column
        plt.title('FeatureMap ' + str(featuremap)) # displays the feature map number
        if activation_min != -1 & activation_max != -1:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin =activation_min, vmax=activation_max, cmap="gray")
        elif activation_max != -1:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmax=activation_max, cmap="gray")
        elif activation_min !=-1:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin=activation_min, cmap="gray")
        else:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", cmap="gray")
In [56]:
# Create a session
with tf.Session() as sess:
    # Restore the saved model
    saver.restore(sess, tf.train.latest_checkpoint('.'))
    
    conv1 = sess.graph.get_tensor_by_name('conv1:0')
    conv2 = sess.graph.get_tensor_by_name('conv2:0')
    conv3 = sess.graph.get_tensor_by_name('conv3:0')
    
    # Analyze the failure of the model to predict a double-curve image
    print('Traffic Signal - Incorrect Classification')
    plt.imshow(X_new_images[12])
    plt.show()
    traffic_signal_class_id = y_new_images_processed[12]
    traffic_signal_indices = np.nonzero(y_train == traffic_signal_class_id)
    print('Sample Training Images for Traffic Signal')
    for i in range(5):
        plt.imshow(X_train[traffic_signal_indices[0][i]])
        plt.show()

    print()
    print('Traffic Signal Visualizations:')
    print()
    
    traffic_signal = X_new_images_processed[12:13]
    print('Traffic Signal - Convolution 1')
    outputFeatureMap(traffic_signal, conv1)
    plt.show()
    print('Traffic Signal - Convolution 2')
    outputFeatureMap(traffic_signal, conv2)
    plt.show()
    print('Traffic Signal - Convolution 3')
    outputFeatureMap(traffic_signal, conv3)
    plt.show()
    
    print()
    print('120 km/h - Incorrect Classification')
    plt.imshow(X_new_images[15])
    plt.show()
    speed_limit_class_id = y_new_images_processed[15]
    speed_limit_indices = np.nonzero(y_train == speed_limit_class_id)
    print('Sample Training Images for 120 km/h')
    for i in range(5):
        plt.imshow(X_train[speed_limit_indices[0][i]])
        plt.show()
    
    print()
    print('120 km/h Visualizations:')
    print()
    speed_limit = X_new_images_processed[15:16]
    print('120 km/h - Convolution 1')
    outputFeatureMap(speed_limit, conv1)
    plt.show()
    print('120 km/h - Convolution 2')
    outputFeatureMap(speed_limit, conv2)
    plt.show()
    print('120 km/h - Convolution 3')
    outputFeatureMap(speed_limit, conv3)
    plt.show()
Traffic Signal - Incorrect Classification
Sample Training Images for Traffic Signal
Traffic Signal Visualizations:

Traffic Signal - Convolution 1
Traffic Signal - Convolution 2
Traffic Signal - Convolution 3
120 km/h - Incorrect Classification
Sample Training Images for 120 km/h
120 km/h Visualizations:

120 km/h - Convolution 1
120 km/h - Convolution 2
120 km/h - Convolution 3